package com.soos.plugin.mybatis.log.spring.boot.interceptor;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.aspectj.weaver.ast.Var;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;

@Intercepts({
        @Signature(type = Executor.class, method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "update",
                args = {MappedStatement.class, Object.class})
})
public class MybatisLogInterceptor implements Interceptor {

    public static final Logger LOGGER = LoggerFactory.getLogger(MybatisLogInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement mappedStatement = (MappedStatement) args[0];
        Object param = null;
        if (args.length > 1) {
            param = args[1];
        }
        String id = mappedStatement.getId();
        Configuration configuration = mappedStatement.getConfiguration();
        BoundSql boundSql = mappedStatement.getBoundSql(param);
        String sql = getSql(boundSql, param, configuration);

        return null;
    }


    /**
     * ==============================================
     *
     * @param boundSql
     * @param param
     * @param configuration
     * @return: java.lang.String
     * @description:
     * @title: getSql
     * @author: WYL
     * @date: 2022/4/8 21:58
     * @since: V1.0.0
     * ==============================================
     */
    private String getSql(BoundSql boundSql, Object param, Configuration configuration) {
        String sql = boundSql.getSql().replaceAll("[\\s]", " ");
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
        if (parameterMappings != null) {
            for (ParameterMapping mapping : parameterMappings) {

                if (mapping.getMode() != ParameterMode.OUT) {
                    Object value;
                    String property = mapping.getProperty();
                    if (boundSql.hasAdditionalParameter(property)) {
                        value = boundSql.getAdditionalParameter(property);
                    } else if (param == null) {
                        value = null;
                    } else if (typeHandlerRegistry.hasTypeHandler(param.getClass())) {
                        value = param;
                    } else {
                        MetaObject metaObject = configuration.newMetaObject(param);
                        value = metaObject.getValue(property);
                    }
                    sql = replaceSql(sql, value);
                }
            }
        }
        return sql;
    }

    /**
     * 替换sql中的?
     *
     * @return
     * @author SOOS
     * @desc
     * @date 2022/3/26 23:28
     */
    private String replaceSql(String sql, Object value) {
        String result;
        if (value != null) {
            if (value instanceof String) {
                result = String.format("'%s'", value);
            } else if (value instanceof Date) {
                result = String.format("'%s'", ((Date) value)
                        .toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDateTime()
                        .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
            } else {
                result = value.toString();
            }
        } else {
            result = "null";
        }
        return sql.replaceFirst("\\?", Matcher.quoteReplacement(result));
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
